package com.shd.edanpei.base;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.Keep;
import android.support.multidex.MultiDex;
import android.util.Log;
import com.shd.edanpei.base.MyApplication;
import com.shd.edanpei.util.DateUtils;
import com.shd.edanpei.util.KillSelfServer;
import com.shd.edanpei.util.ToastUtil;
import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixApplication;
import com.taobao.sophix.SophixEntry;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;

import java.util.ArrayList;
import java.util.List;

public class SophixStubApplication extends SophixApplication {
    private final String TAG = "SophixStubApplication";
    public static final String appkey = "";
    public static final String appId = "25657229";
    public static final String appSecret = "4fae3beb1445bbaea27f9453447cbedb";
    public static final String rsaSecret = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwkOQmbTrrkQ7fr4z5hOl4nv67LHqAyzBW+EWBBkDFYHk0cqqPEZnRxjGtCxg2F+HvUk77bCIV87tbPoToQ/Zpd6stlbOthKoBcsNw2gGWVyEfVXT2uPusjN77fHbOjAAEi3hv7c52FBOoAuCGAK7KG5fW8/xmSDFpXm2Oi6LSX4SYOOTwc5n3PGuCYN1+thow7jYbS1BLWutDV15ogX/jpDElbjezpMM66WjW+dOAzq6xQm5ydNXICp8QQxS4TAdzkZQTuqvike20gVZW/7/oSSS0vIEmDuvNOjzgAETwWzKY0GFITWU1mXy72WnFuYnuJ5RVlAQbXvhPZFvE22udAgMBAAECggEAePuu+Q2bc9I/aNI3PLnv6DC5xrMhdaLEirMvnMsWEqiaJG/1onai+XRekX2qp1YSABRb/jcH3BbX6BucojH/ZCEVb/TF2z2t57QlauxWbhdhoMDDllMGUCNuns+X8MtJL9QJQFioQYxcM6FVCzzoh6AEmMsxxTvub46+bxALDy4wRKgVSi8x4hh6mvnXXS0xVwTC8HN+M/BqdVcGnoixS27YGt5qBhQW6YY7V/ZHJOompp2lbHmkwfsM7ONj14HQu9AKcmlS7PX7M2Eh6gtiaZJRZPnAw+tyo3Q4lZsEEvys8q12s8MEn8qK/nvu6RFWcDC4zO5GCAJPVlpyFPQ82QKBgQD80vCqyvbjK1/fbEWGacVoFLw1g4vnbDp+F7gxSIVpZycMbM8i7Dih6bFV68cBeOtcVkAbZn0+n6SoeQFBg4NjIFxYhGyuMqKRg+Q97icd1vYtbgtD3RWoGQuH6Hy3slJCbdYmYkKR8+iOpjVlvip22z0GGeoY5m1/9CA3bYI/owKBgQCyyLZGj63JP4dT5BjLsQZeAsH+SGD0gpllJSMgjS6En/4cCOiSHSlnAYnF1NqCPz8p/U8gFLetcEw/Wy4qHYycctq2w0kr/7fbMial8TaaN8n1d6ICIqytQTFFpIYhXESF9E3xsYFdirwH25EsH4vih1Hk3UZ1CgC9mDhoQKVbvwKBgQDCdtnI9Q7LkyxOJPChP7Aoq3JM0x8EZXnkTQhPWBHODhq58uOsX/f7ik3t4coTdtfKEUmECeQiDBdRwqlVo/umflipeUpC/w2OUd14STtrN1HphbBChcZHouP8qLVtckrVb7h9k6zSqMJjHrMJzCjLfTzF+Z7Xgj4NYlB5cdDycwKBgHx/9R7yEy1gBhdPckz2e96fwQQY1xuujq+2yt1yM4C8AbL4KS0HDbvjgFO5xGiLLqtI8P8ALmCjIRXFo0JEzZRtDw3StHPlYd1M8UkBzupaC1Pa+YDPMLx995ft2FIG9NjrphO3bsT7RbGbH19AoKMhZNAhn10FmDpvdGh1DDH1AoGBAOd1yTFp7vQIobrKNDeiGUwgK4J2AvVqQEO29SDQpA5qstQpSTXCwJBYjPG5UsFVL/TLgjLVua/UheExMh8wA4oAB+oZN3uwMYzQ5viV/HJ/aJZtw61JyfXFWfYoVSKnJNo1Axvxr1HZyfKySafmX1I2gWn83TOEjYZwojlzdsRI";
    public static final String httpdns_accountId = "";
    public static final String httpdns_secretKey = "";


    @Keep
    @SophixEntry(MyApplication.class)//只有这里改成自己的Application类，下面static不要改
    static class RealApplicationStub {
    }


    //这里不能调用非系统API的类

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        //如用到MultiDex，必须在此初始化
        MultiDex.install(this);

        //这里不能调用非系统API的类
        initSophix();

        //这里可以调用非系统API的类
    }

    private void initSophix() {
        String appVersion = "0.0.0";
        try {
            appVersion = getBaseContext().getPackageManager()
                    .getPackageInfo(this.getPackageName(), 0)
                    .versionName+"";
        } catch (Exception e) {
            appVersion = "1.0.0";
        }

        List<String> tags = new ArrayList<>();
        tags.add("1.8");
        final SophixManager instance = SophixManager.getInstance();
        instance.setContext(this)
                .setAppVersion(appVersion)
                //.setAppVersion("tags")//与控制台创建的版本号对应，否则拉取不到补丁
                .setTags(tags)
                .setAesKey(null)
                .setEnableDebug(true)
                .setEnableFullLog()
                .setSecretMetaData(appId, appSecret, rsaSecret)
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
                        String msg = new StringBuilder("").append("Mode:").append(mode)
                                .append(" Code:").append(code)
                                .append(" Info:").append(info)
                                .append(" HandlePatchVersion:").append(handlePatchVersion).toString();
                        if (msgDisplayListener != null) {
                            msgDisplayListener.handle(msg);
                        } else {
                            cacheMsg.append("\n").append(msg);
                        }
                        Log.i(TAG, "sophix--------"+code);
                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                            Log.i(TAG, "sophix load patch success!");
                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                            // 如果需要在后台重启，建议此处用SharePreference保存状态。
                            Log.i(TAG, "sophix preload patch success. restart app to make effect.");
                            ToastUtil.showToast("E单配app开小差了，需要重启!"+MyApplication.getInstance());
                            restartAPP(SophixStubApplication.this,1000);
                        }
                    }
                }).initialize();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences sharedPreferences=getSharedPreferences("fix_time_key",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putInt(DateUtils.getData(),sharedPreferences.getInt(DateUtils.getData(),1));
        editor.commit();
//        ToastUtil.showToast("code"+sharedPreferences.getInt(DateUtils.getData(),0));
        if(sharedPreferences.getInt(DateUtils.getData(),0)<30 ) {
            //SophixManager.getInstance().queryAndLoadNewPatch();暂时屏蔽
            int i=sharedPreferences.getInt(DateUtils.getData(),0);
            editor.putInt(DateUtils.getData(),i+1);
            editor.commit();
        }
    }


    public interface MsgDisplayListener {
        void handle(String msg);
    }

    public static MsgDisplayListener msgDisplayListener = null;
    public static StringBuilder cacheMsg = new StringBuilder();



    public static void restartAPP(Context context, long Delayed){
        /**开启一个新的服务，用来重启本APP*/
        Intent intent1=new Intent(context,KillSelfServer.class);
        intent1.putExtra("PackageName",context.getPackageName());
        intent1.putExtra("Delayed",Delayed);
        context.startService(intent1);
        /**杀死整个进程**/
        android.os.Process.killProcess(android.os.Process.myPid());}

}
